package org.jeecg.modules.lab.items.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.cronJob.MyEnum;
import org.jeecg.common.cronJob.entity.LabCronJob;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.lab.cronJob.service.ILabCronJobService;
import org.jeecg.modules.lab.entrust.entity.*;
import org.jeecg.modules.lab.entrust.service.ILabEntrustItemsService;
import org.jeecg.modules.lab.entrust.service.ILabWscientificService;
import org.jeecg.modules.lab.entrust.service.ILabWtemporarilyService;
import org.jeecg.modules.lab.items.entity.LabItems;
import org.jeecg.modules.lab.items.item.service.ILabItemsService;
import org.jeecg.modules.lab.items.record.service.*;
import org.jeecg.modules.lab.items.temp2.entity.LabItemsTemp2Basic;
import org.jeecg.modules.lab.items.temp2.entity.LabItemsTemp2Norm;
import org.jeecg.modules.lab.items.temp2.entity.LabItemsTemp2Person;
import org.jeecg.modules.lab.items.temp2.entity.LabItemsTemp2Target;
import org.jeecg.modules.lab.items.temp2.service.ILabItemsTemp2BasicService;
import org.jeecg.modules.lab.items.temp2.service.ILabItemsTemp2NormService;
import org.jeecg.modules.lab.items.temp2.service.ILabItemsTemp2PersonService;
import org.jeecg.modules.lab.items.temp2.service.ILabItemsTemp2TargetService;
import org.jeecg.modules.lab.items.vo.LabEntrustItemPage;
import org.jeecg.modules.lab.util.FlowNumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: 实验项目表
 * @Author: jeecg-boot
 * @Date: 2023-08-10
 * @Version: V1.0
 */
@Api(tags = "实验项目")
@RestController
@RequestMapping("/items/labEntrustItems")
@Slf4j
public class LabEntrustItemsController extends JeecgController<LabEntrustItems, ILabEntrustItemsService> {
    @Autowired
    private ILabEntrustItemsService labEntrustItemsService;

    @Autowired
    private ILabItemsService labItemsService;

    @Autowired
    private ILabItemsTemp2BasicService labItemsTemp2BasicService;

    @Autowired
    private ILabItemsTemp2NormService labItemsTemp2NormService;

    @Autowired
    private ILabItemsTemp2PersonService labItemsTemp2PersonService;

    @Autowired
    private ILabItemsTemp2TargetService labItemsTemp2TargetService;

    @Autowired
    private ILabItemsRecordSampleService labItemsRecordSampleService;

    @Autowired
    private ILabItemsRecordDeviceService labItemsRecordDeviceService;

    @Autowired
    private ILabItemsRecordNormService labItemsRecordNormService;

    @Autowired
    private ILabItemsRecordTargetService labItemsRecordTargetService;

    @Autowired
    private ILabItemsRecordPersonService labItemsRecordPersonService;

    @Autowired
    private ILabWscientificService labWscientificService;

    @Autowired
    private ILabWtemporarilyService labWtemporarilyService;

    @Autowired
    private ILabCronJobService labCronJobService;


    /**
     * 分页列表查询
     *
     * @param labEntrustItems
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "实验项目表-分页列表查询")
    @ApiOperation(value = "实验项目-分页列表查询", notes = "实验项目-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<LabEntrustItems>> queryPageList(LabEntrustItems labEntrustItems,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "50") Integer pageSize,
                                                        HttpServletRequest req) {
        QueryWrapper<LabEntrustItems> queryWrapper = QueryGenerator.initQueryWrapper(labEntrustItems, req.getParameterMap());
        Page<LabEntrustItems> page = new Page<LabEntrustItems>(pageNo, pageSize);
        IPage<LabEntrustItems> pageList = labEntrustItemsService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    @ApiOperation(value = "实验项目-重复实验项目", notes = "实验项目-重复实验项目")
    @GetMapping(value = "/ItemsList")
    public Result<List<LabEntrustItems>> queryItemsList(@RequestParam(name = "entrustId", defaultValue = "") String entrustId,
                                                        @RequestParam(name = "userId", defaultValue = "") String userId) {
        List<LabEntrustItems> labEntrustItems = labEntrustItemsService.queryItemsList(entrustId,userId);
        return Result.OK(labEntrustItems);
    }
    /**
     * 添加
     *
     * @param labEntrustItems
     * @return
     */
    @AutoLog(value = "实验任务-添加")
    @ApiOperation(value = "实验任务-添加", notes = "实验任务-添加")
//	@RequiresPermissions("items:lab_entrust_items:add")
    @PostMapping(value = "/addItemt")
    public Result<LabEntrustItems> addItemt(@RequestBody LabEntrustItems labEntrustItems) {
        String type = labEntrustItems.getEntrustType();
        String itemId =labEntrustItems.getItemId();
        LabItems byId = labItemsService.getById(itemId);
        if ("科研项目".equals(type) || "临时任务".equals(type)) {
            if ("科研项目".equals(type)) {
                LabWscientific byId1 = labWscientificService.getById(labEntrustItems.getEntrustId());
                if(byId1 != null){
                    //查询总的数量
                    Integer s = labItemsService.selctAll(labEntrustItems.getEntrustId());
                    byId1.setCounting(s+1);
                    labWscientificService.updateById(byId1);
                }
            } else {
                LabWtemporarily byId1 = labWtemporarilyService.getById(labEntrustItems.getEntrustId());
                if(byId1 != null){
                    //查询总的数量
                    Integer s = labItemsService.selctAll(labEntrustItems.getEntrustId());
                    byId1.setCounting(s+1);
                    labWtemporarilyService.updateById(byId1);
                }
            }
        }
        labEntrustItems.setItemId(byId.getId());
        labEntrustItems.setItemName(byId.getName());
        labEntrustItems.setItemStatus("待实验");
        labEntrustItems.setSynFlag("0");
        //添加项目的标准和标准类型
        labEntrustItemsService.save(labEntrustItems);
        //插入项目模板-样品信息
        labItemsRecordSampleService.insertSamData(labEntrustItems);
        //插入项目模板-检测条件信息
        labItemsRecordNormService.insertNormData(labEntrustItems);
        //插入项目模板-检测信息
        labItemsRecordTargetService.insertTargetData(labEntrustItems);
        //插入项目模板-人员信息
        labItemsRecordPersonService.insertPersonData(labEntrustItems);
        if (MyEnum.sync) {
            long time = new Date().getTime();
            if (("科研项目".equals(type) || "临时任务".equals(type))) {
                List<LabCronJob> jobs = new ArrayList<>();
                if(itemId ==null  || "".equals(itemId)){
                    jobs.add(new LabCronJob("lab_items", "0", time, 1));
                }
                jobs.add(new LabCronJob("lab_entrust_items", "0", time, 2));
                jobs.add(new LabCronJob("lab_items_record_sample", "0", time, 3));
                jobs.add(new LabCronJob("lab_items_record_norm", "0", time, 4));
                jobs.add(new LabCronJob("lab_items_record_target", "0", time, 5));
                jobs.add(new LabCronJob("lab_items_record_person", "0", time, 6));
                labCronJobService.saveBatch(jobs);
            } else {
                LabCronJob job = new LabCronJob("lab_entrust_items", "0", time, 1);
                labCronJobService.save(job);
            }
        }
        return Result.OK(labEntrustItems);
    }
    /**
     * 添加
     *
     * @param labEntrustItems
     * @return
     */
    @AutoLog(value = "实验项目-添加")
    @ApiOperation(value = "实验项目-添加", notes = "实验项目-添加")
//	@RequiresPermissions("items:lab_entrust_items:add")
    @PostMapping(value = "/add")
    public Result<LabEntrustItems> add(@RequestBody LabEntrustItems labEntrustItems) {
        String type = labEntrustItems.getEntrustType();
        if ("科研项目".equals(type) || "临时任务".equals(type)) {
            LabItems items = new LabItems();
            items.setName(labEntrustItems.getItemName());
            if ("科研项目".equals(type)) {
                items.setType("D");
            } else {
                items.setType("E");
            }
            items.setLevel("3");
            items.setSynFlag("0");
            labItemsService.save(items);
            labEntrustItems.setItemId(items.getId());
        }
        labEntrustItemsService.save(labEntrustItems);

        if (MyEnum.sync) {
            long time = new Date().getTime();
            if ("科研项目".equals(type) || "临时任务".equals(type)) {
                List<LabCronJob> jobs = new ArrayList<>();
                jobs.add(new LabCronJob("lab_items", "0", time, 1));
                jobs.add(new LabCronJob("lab_entrust_items", "0", time, 2));
                labCronJobService.saveBatch(jobs);
            } else {
                LabCronJob job = new LabCronJob("lab_entrust_items", "0", time, 1);
                labCronJobService.save(job);
            }
        }
        return Result.OK(labEntrustItems);
    }

    /**
     * 编辑
     *
     * @param labEntrustItems
     * @return
     */
    @AutoLog(value = "实验项目-编辑")
    @ApiOperation(value = "实验项目-编辑", notes = "实验项目-编辑")
//	@RequiresPermissions("items:lab_entrust_items:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody LabEntrustItems labEntrustItems) {
        labEntrustItems.setSynFlag("1");
        labEntrustItemsService.updateById(labEntrustItems);
        String item_id = labEntrustItems.getItemId();
        String task_id = labEntrustItems.getEntrustId();

        //科研项目和临时任务：生成了项目模板，需要更新对应模板数据的task_id
        if ("科研项目".equals(labEntrustItems.getEntrustType()) || "临时任务".equals(labEntrustItems.getEntrustType())) {
            //样品
            QueryWrapper<LabItemsRecordSample> samQueryWrapper = new QueryWrapper<>();
            samQueryWrapper.eq("item_id", item_id);
            LabItemsRecordSample sample = new LabItemsRecordSample();
            sample.setTaskId(task_id);
            sample.setSynFlag("1");
            labItemsRecordSampleService.update(sample, samQueryWrapper);

            //设备
            QueryWrapper<LabItemsRecordDevice> devQueryWrapper = new QueryWrapper<>();
            devQueryWrapper.eq("item_id", item_id);
            LabItemsRecordDevice device = new LabItemsRecordDevice();
            device.setTaskId(task_id);
            device.setSynFlag("1");
            labItemsRecordDeviceService.update(device, devQueryWrapper);

            //条件
            QueryWrapper<LabItemsRecordNorm> normQueryWrapper = new QueryWrapper<>();
            normQueryWrapper.eq("item_id", item_id);
            LabItemsRecordNorm norm = new LabItemsRecordNorm();
            norm.setTaskId(task_id);
            norm.setSynFlag("1");
            labItemsRecordNormService.update(norm, normQueryWrapper);

            //指标
            QueryWrapper<LabItemsRecordTarget> targetQueryWrapper = new QueryWrapper<>();
            targetQueryWrapper.eq("item_id", item_id);
            LabItemsRecordTarget target = new LabItemsRecordTarget();
            target.setTaskId(task_id);
            target.setSynFlag("1");
            labItemsRecordTargetService.update(target, targetQueryWrapper);

            //人员
            QueryWrapper<LabItemsRecordPerson> personQueryWrapper = new QueryWrapper<>();
            targetQueryWrapper.eq("item_id", item_id);
            LabItemsRecordPerson person = new LabItemsRecordPerson();
            person.setTaskId(task_id);
            person.setSynFlag("1");
            labItemsRecordPersonService.update(person, personQueryWrapper);
        }

        if (MyEnum.sync) {
            long time = new Date().getTime();
            if ("科研项目".equals(labEntrustItems.getEntrustType()) || "临时任务".equals(labEntrustItems.getEntrustType())) {
                List<LabCronJob> jobs = new ArrayList<>();
                jobs.add(new LabCronJob("lab_entrust_items", "1", time, 1));
                jobs.add(new LabCronJob("lab_items_record_sample", "1", time, 2));
                jobs.add(new LabCronJob("lab_items_record_device", "1", time, 3));
                jobs.add(new LabCronJob("lab_items_record_norm", "1", time, 4));
                jobs.add(new LabCronJob("lab_items_record_target", "1", time, 5));
                jobs.add(new LabCronJob("lab_items_record_person", "1", time, 6));
                labCronJobService.saveBatch(jobs);
            } else {
                LabCronJob job = new LabCronJob("lab_entrust_items", "1", time, 1);
                labCronJobService.save(job);
            }
        }
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "实验项目-通过id删除")
    @ApiOperation(value = "实验项目-通过id删除", notes = "实验项目-通过id删除")
//	@RequiresPermissions("items:lab_entrust_items:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        LabEntrustItems labEntrustItems = labEntrustItemsService.getById(id);
        if (labEntrustItems == null) {
            return Result.error("未找到对应数据");
        }
        labEntrustItemsService.removeById(id);

        //科研项目和临时任务:删除对应项目和模板数据
        if ("科研项目".equals(labEntrustItems.getEntrustType()) || "临时任务".equals(labEntrustItems.getEntrustType())) {
            String item_id = labEntrustItems.getItemId();
            //项目
            labItemsService.removeById(item_id);
            //基础信息
            QueryWrapper<LabItemsTemp2Basic> basicQueryWrapper = new QueryWrapper<>();
            basicQueryWrapper.eq("items_id", item_id);
            labItemsTemp2BasicService.remove(basicQueryWrapper);
            //检测条件
            QueryWrapper<LabItemsTemp2Norm> normQueryWrapper = new QueryWrapper<>();
            normQueryWrapper.eq("items_id", item_id);
            labItemsTemp2NormService.remove(normQueryWrapper);
            //检测指标
            QueryWrapper<LabItemsTemp2Target> TargetQueryWrapper = new QueryWrapper<>();
            TargetQueryWrapper.eq("items_id", item_id);
            labItemsTemp2TargetService.remove(TargetQueryWrapper);
            //实验人员
            QueryWrapper<LabItemsTemp2Person> personQueryWrapper = new QueryWrapper<>();
            personQueryWrapper.eq("items_id", item_id);
            labItemsTemp2PersonService.remove(personQueryWrapper);
        }

        if (MyEnum.sync) {
            long time = new Date().getTime();
            if ("科研项目".equals(labEntrustItems.getEntrustType()) || "临时任务".equals(labEntrustItems.getEntrustType())) {
                List<LabCronJob> jobs = new ArrayList<>();
                String condition1 = "id='" + id + "'";
                String condition2 = "id='" + labEntrustItems.getItemId() + "'";
                String condition3 = "items_id='" + labEntrustItems.getItemId() + "'";
                jobs.add(new LabCronJob("lab_entrust_items", "2", condition1, time, 1));
                jobs.add(new LabCronJob("lab_items", "2", condition2, time, 2));
                jobs.add(new LabCronJob("lab_items_temp2_basic", "2", condition3, time, 3));
                jobs.add(new LabCronJob("lab_items_temp2_norm", "2", condition3, time, 4));
                jobs.add(new LabCronJob("lab_items_temp2_target", "2", condition3, time, 5));
                jobs.add(new LabCronJob("lab_items_temp2_person", "2", condition3, time, 6));
                labCronJobService.saveBatch(jobs);
            } else {
                String condition = "id='" + id + "'";
                LabCronJob job = new LabCronJob("lab_entrust_items", "2", condition, time, 1);
                labCronJobService.save(job);
            }
        }
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "实验项目-批量删除")
    @ApiOperation(value = "实验项目-批量删除", notes = "实验项目-批量删除")
//	@RequiresPermissions("items:lab_entrust_items:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.labEntrustItemsService.removeByIds(Arrays.asList(ids.split(",")));

        if (MyEnum.sync) {
            long time = new Date().getTime();
            String[] idList = ids.split(",");
            labCronJobService.saveCronBatch("lab_entrust_items", "2", time, idList);
        }
        return Result.OK("批量删除成功!");
    }


    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "实验项目-通过id查询")
    @ApiOperation(value = "实验项目-通过id查询", notes = "实验项目-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<LabEntrustItems> queryById(@RequestParam(name = "id", required = true) String id) {
        LabEntrustItems labEntrustItems = labEntrustItemsService.getById(id);
        if (labEntrustItems == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(labEntrustItems);
    }


    /**
     * 通过任务id和项目id查询
     *
     * @param entrustId
     * @param itemId
     * @return
     */
    @ApiOperation(value = "实验项目-通过任务id和项目id查询", notes = "实验项目-通过任务id和项目id查询")
    @GetMapping(value = "/queryByEntIdAndItemId")
    public Result<LabEntrustItems> queryByEntIdAndItemId(@RequestParam(name = "entrustId", required = true) String entrustId,@RequestParam(name = "itemId", required = true) String itemId) {
        QueryWrapper<LabEntrustItems> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("entrust_id",entrustId);
        queryWrapper.eq("item_id", itemId);
        LabEntrustItems labEntrustItems = labEntrustItemsService.getOne(queryWrapper);
        if (labEntrustItems == null ) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(labEntrustItems);
    }


    /**
     * 实验项目-科研项目列表
     * @param kyId
     * @return
     */
    @ApiOperation(value = "实验项目-科研项目列表", notes = "实验项目-科研项目列表")
    @GetMapping(value = "/getEntrustItemList")
    public Result<List<LabEntrustItemPage>> getEntrustItemList(@RequestParam(name = "kyId", required = true) String kyId) {
        List<LabEntrustItemPage> labEntrustItems = labEntrustItemsService.getEntrustItemList(kyId);
        return Result.OK(labEntrustItems);
    }


    //    @AutoLog(value = "科研项目-生成实验模板")
    @ApiOperation(value = "实验项目-（科研、临时）生成实验模板", notes = "实验项目-（科研、临时）实验模板")
    @PostMapping(value = "/createTemp2")
    public Result<String> createTemp2(@RequestBody LabEntrustItems labEntrustItems) {

        String entrust_id = labEntrustItems.getEntrustId();
        if ("".equals(entrust_id) || entrust_id == null) {
            labEntrustItems.setEntrustId(FlowNumberUtil.getRandomId());
        }
        String type = labEntrustItems.getEntrustType();
        //更新项目的发布时间和截至时间
        if ("科研项目".equals(type)) {
            LabWscientific labWscientific = labWscientificService.getById(labEntrustItems.getEntrustId());
            if (labWscientific != null) {
                labEntrustItems.setPubDate(labWscientific.getKyStartDate());
                labEntrustItems.setFinDate(labWscientific.getKyEndDate());
            }
        } else if ("临时任务".equals(type)) {
            LabWtemporarily labWtemporarily = labWtemporarilyService.getById(labEntrustItems.getEntrustId());
            if (labWtemporarily != null) {
                labEntrustItems.setPubDate(labWtemporarily.getStartDate());
                labEntrustItems.setFinDate(labWtemporarily.getEndDate());
            }
        }
        //1、更新实验项目记录
        labEntrustItems.setItemStatus("待实验");
        labEntrustItems.setItemStartTime(DateUtils.getDate());
        labEntrustItems.setSynFlag("1");
        labEntrustItemsService.updateById(labEntrustItems);

        //2、插入实验模板数据到实验记录表中（sampl、norm、target、per）
        //2.1插入sampl
        labItemsRecordSampleService.kyInsertSamData(labEntrustItems);
        //2.2插入norm
        labItemsRecordNormService.kyInsertNormData(labEntrustItems);
        //2.3插入target
        labItemsRecordTargetService.kyInsertTargetData(labEntrustItems);
        //2.4插入person
        labItemsRecordPersonService.kyInsertPersonData(labEntrustItems);

        if (MyEnum.sync) {
            long time = new Date().getTime();
            List<LabCronJob> jobs = new ArrayList<>();
            jobs.add(new LabCronJob("lab_entrust_items", "1", time, 1));
            String condition="item_id='"+labEntrustItems.getItemId()+"'";
            jobs.add(new LabCronJob("lab_items_record_sample", "2",condition, time, 2));
            jobs.add(new LabCronJob("lab_items_record_sample", "0", time, 3));
            jobs.add(new LabCronJob("lab_items_record_norm", "2",condition, time, 4));
            jobs.add(new LabCronJob("lab_items_record_norm", "0", time, 5));
            jobs.add(new LabCronJob("lab_items_record_target", "2",condition, time, 6));
            jobs.add(new LabCronJob("lab_items_record_target", "0", time, 7));
            jobs.add(new LabCronJob("lab_items_record_person", "2",condition, time, 8));
            jobs.add(new LabCronJob("lab_items_record_person", "0", time, 9));
            labCronJobService.saveBatch(jobs);
        }

        return Result.OK("生成模板成功！");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param labEntrustItems
     */
//    @RequiresPermissions("items:lab_entrust_items:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LabEntrustItems labEntrustItems) {
        return super.exportXls(request, labEntrustItems, LabEntrustItems.class, "实验项目表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
//    @RequiresPermissions("items:lab_entrust_items:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LabEntrustItems.class);
    }

}
